package com.tyqx.hashchainbackend.controller;

// import com.alibaba.fastjson.JSON;
import com.tyqx.hashchainbackend.service.SysRoleService;
import com.tyqx.hashchainbackend.service.SysUserRoleService;
import com.tyqx.hashchainbackend.service.SysUserService;
import com.tyqx.hashchainbean.module.SysUser;
import com.tyqx.hashchainbean.vo.*;
import io.swagger.annotations.Api;
import hashchainutil.common.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.expression.Ids;

import javax.annotation.Resource;
import java.util.*;

@Api(description = "系统用户管理")
@Controller
@RequestMapping("/sysUser")
public class SysUserController {

    Logger logger = Logger.getLogger(this.getClass());
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysRoleService sysRoleService;


    //分页查询用户信息
    @RequestMapping(value = "/queryPage", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public BackendPage<List<SysUser>> queryPage(int page, int limit, String userCode) {
        //构建参数
        Map<String, Object> param = new HashMap();
        if (EmptyUtils.isNotEmpty(userCode))
            param.put("userCode", userCode);
        try {
            BackendPage<List<SysUser>> result = sysUserService.queryPageByMap(param, page, limit);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new BackendPage("查询异常");
        }
    }

    @RequestMapping(value = "/sysUserSave", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String sysUserSave(SysUserSaveVO sysUserSaveVO) {
        // 返回信息
        String message = "";
        //添加系统用户
        if (EmptyUtils.isEmpty(sysUserSaveVO.getUserCode())) {
            message = "用户账号不能为空";
        }
        if (message == "" && EmptyUtils.isEmpty(sysUserSaveVO.getUserEmail())) {
            message = "用户邮箱不能为空";
        }
        if (message == "" && EmptyUtils.isEmpty(sysUserSaveVO.getUserName())) {
            message = "用户名称不能为空";
        }
        if (message == "" && EmptyUtils.isEmpty(sysUserSaveVO.getUserPassword())) {
            message = "用户密码不能为空";
        }
        if (message == "" && EmptyUtils.isEmpty(sysUserSaveVO.getUserPhone())) {
            message = "手机号不能为空";
        }
        // 登录
        if (EmptyUtils.isEmpty(message)) {

            try {
                if (sysUserService.save(sysUserSaveVO) > 0) {
                    message = "success";
                } else {
                    message = "error";
                }
            } catch (Exception e) {
                e.printStackTrace();
                message = "添加异常";
            }
        }
        return message;
    }

    //分配角色
    @RequestMapping(value = "/sysUserRoleSaveyBUserId", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto sysUserRoleSaveByUserId(@RequestParam("id") String id,@RequestParam("userId") Long userId) throws Exception {
        if("".equals(id)){
            sysUserRoleService.removeByUrUserId(userId);
            return DtoUtil.returnSuccess("success");
        }
        String[] IDs = id.split(",");
        //之前已经拥有的角色
        List<SysUserRoleVO> sysUserRoleVOS = sysUserRoleService.getSysRoleByUserId(userId);
        //已经拥有的角色+先赋予的角色
        List<Integer> roleIdList=new ArrayList<>();
        if(IDs.length>0){
            for (int b=0;b< IDs.length;b++){
                roleIdList.add(Integer.valueOf(IDs[b]));
            }
        }else{
            sysUserRoleService.removeByUrUserId(userId);
            return DtoUtil.returnSuccess("success");
        }

        List<SysUserRoleVO> sysUserRoleVOS1=new ArrayList<>();

        for (int i = 0; i <sysUserRoleVOS.size(); i++) {
            for (int j = 0; j < roleIdList.size(); j++) {
                    if (roleIdList.get(j) == sysUserRoleVOS.get(i).getUrRoleId()) {
                            roleIdList.remove(j);
                        sysUserRoleVOS1.add(sysUserRoleVOS.get(j));
                    }
            }
        }

        List<SysUserRoleVO> sysUserRoleVOS2=new ArrayList<>();

        for (int i = 0; i <sysUserRoleVOS.size(); i++) {
            for (int j = 0; j < sysUserRoleVOS1.size(); j++) {
                if (sysUserRoleVOS1.get(j).getUrRoleId() == sysUserRoleVOS.get(i).getUrRoleId()) {
                    sysUserRoleVOS2.remove(sysUserRoleVOS1.get(j));
                }
            }
        }
        int count = 0;
        String message = "";
       /* if(sysUserRoleVOS2.size()>0){
            for (int i = 0; i <sysUserRoleVOS2.size(); i++) {
                count += sysUserRoleService.removeByUrRoleId(Long.valueOf(sysUserRoleVOS2.get(i).getUrRoleId()));
            }
        }*/
        if(roleIdList.size()>0) {
            for (int k = 0; k < roleIdList.size(); k++) {
                SysUserRoleSave sysUserRoleSave = new SysUserRoleSave();
                sysUserRoleSave.setUrUserId(userId);
                sysUserRoleSave.setUrRoleId(roleIdList.get(k));
                sysUserRoleSave.setUrCreationDate(new Date());
                count += sysUserRoleService.save(sysUserRoleSave);

            }
        }
        if (count > 0) {
            message = "success";
            return DtoUtil.returnSuccess(message);
        }else {
            message="error";
            return DtoUtil.returnFail(message,"100001");
        }

    }


    //查询当前用户已有的角色
    @RequestMapping(value = "/queryRoleListByUrUserId", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public List<SysUserRoleVO> queryRoleListByUrUserId(Long urUserId) throws Exception {
        return sysUserRoleService.getSysRoleByUserId(urUserId);

    }

    //查询当前用户已有的角色
    @RequestMapping(value = "/modifyUserStatus", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public String modifyUserStatus(@RequestParam Boolean userActivate, @RequestParam Long userId) {
        String isFlag = "";
        if (userActivate) {
            if (sysUserService.updateActivate(1, userId) > 0) {
                isFlag = "更改成功";
            }
        }else{
            if (sysUserService.updateActivate(0, userId) > 0) {
                isFlag = "更改成功";
            }
        }
        return isFlag;
    }

    //修改
    @RequestMapping(value = "/modify", method = RequestMethod.GET, produces = "application/json; utf-8")
    @ResponseBody
    public String getUserModify(SysUserModifyVO modifyVO) {
        String errorCode = "";
        if (EmptyUtils.isEmpty(modifyVO.getUserCode())) {
            errorCode = "登录账号不能为空";
        }
        if (EmptyUtils.isEmpty(modifyVO.getUserName())) {
            errorCode = "用户名不可为空";
        }
        if (EmptyUtils.isEmpty(modifyVO.getUserSex())) {
            errorCode = "性别不可为空";
        }
        if (EmptyUtils.isEmpty(modifyVO.getUserPhone())) {
            errorCode = "手机号不可为空";
        }
        if (EmptyUtils.isEmpty(modifyVO.getUserEmail())) {
            errorCode = "邮箱不可为空";
        }
        if (EmptyUtils.isEmpty(errorCode)) {
            try {
                Integer result = sysUserService.getUserModify(modifyVO);
                if (result > 0) {
                    errorCode = "0";
                } else {
                    errorCode = "1";
                }
            } catch (Exception e) {
                e.printStackTrace();
                errorCode = "修改异常";
            }
        }
        return errorCode;
    }


    @RequestMapping(value = "/updatePassword", method = RequestMethod.GET, produces = "application/json; utf-8")
    @ResponseBody
    public String updatePassword(SysUpdaUserPwdVO sysUpdaUserPwdVO, @RequestParam String password) {
        System.err.println("52135==================");
        String errorCode = "";

        if (!sysUpdaUserPwdVO.getUserPassword().equals(password)) {
            return "两次密码不同";
        }
        for (int i = 0; i < 20; i++) {
            System.err.println(password);
            System.err.println(sysUpdaUserPwdVO.getUserId());
        }

        for (int i = 0; i < 20; i++) {
            System.err.println(password);
            System.err.println(sysUpdaUserPwdVO.getUserId());
        }
        try {

            Integer result = sysUserService.updateUserPwdById(sysUpdaUserPwdVO);
            if (result > 0) {
                errorCode = "0";
            } else {
                errorCode = "1";
            }
        } catch (Exception e) {
            e.printStackTrace();
            errorCode = "修改异常";
        }

        return errorCode;
    }

    @RequestMapping(value = "/delActivate", method = RequestMethod.POST, produces = "application/json; utf-8")
    @ResponseBody
    public String delActivate(@RequestParam Integer userActivate,@RequestParam Long userId){
        String returnCode = "";
        try{

            if(userActivate==2){
                if(sysUserRoleService.getSysRoleByUserId(userId).size()>0){
                    if(sysUserRoleService.removeByUrUserId(userId)>0){
                        if(sysUserService.delActivate(userActivate,userId)>0){
                            returnCode="用户删除成功";
                        }else {
                            returnCode="用户删除失败";
                        }
                    }else{
                        returnCode="删除用户角色失败";
                    }
                }else{
                    if(sysUserService.delActivate(userActivate,userId)>0){
                        returnCode="用户删除成功";
                    }else {
                        returnCode="用户删除失败";
                    }
                }

            }

        }catch(Exception e){
            e.printStackTrace();
            returnCode="用户删除异常";

        }
        return returnCode;


    }

}
